<?php

namespace App\Http\Controllers;

use App\Constants\AppConstants;
use App\Models\Coupon;
use App\Models\UserCoupon;
use App\Services\CouponService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

/**
 * 前台优惠券控制器
 */
class CouponController extends Controller
{
    protected CouponService $couponService;

    public function __construct(CouponService $couponService)
    {
        $this->couponService = $couponService;
    }

    /**
     * 优惠券中心 - 显示可领取的优惠券
     */
    public function index(Request $request): Response
    {
        $query = Coupon::with(['userCoupons' => function ($q) {
                $q->where('user_id', auth()->id());
            }])
            ->available()
            ->orderBy('sort_order', 'desc')
            ->orderBy('created_at', 'desc');

        // 筛选类型
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        // 筛选适用范围
        if ($request->filled('applicable_type')) {
            $query->where('applicable_type', $request->applicable_type);
        }

        $coupons = $query->paginate(AppConstants::PAGINATION_SHOP_DEFAULT);

        // 添加用户领取状态
        $userId = auth()->id();
        $coupons->getCollection()->transform(function ($coupon) use ($userId) {
            if ($userId) {
                $checkResult = $coupon->canUserReceive($userId);
                $coupon->can_receive = $checkResult['can_receive'];
                $coupon->receive_reason = $checkResult['reason'];
                $coupon->has_received = $coupon->userCoupons->where('user_id', $userId)->count() > 0;
            } else {
                $coupon->can_receive = false;
                $coupon->receive_reason = '请先登录';
                $coupon->has_received = false;
            }
            return $coupon;
        });

        return Inertia::render('Shop/Coupons/Index', [
            'coupons' => $coupons,
            'filters' => $request->only(['type', 'applicable_type']),
        ]);
    }

    /**
     * 我的优惠券
     */
    public function myCoupons(Request $request): Response
    {
        $userId = auth()->id();
        if (!$userId) {
            return redirect()->route('login');
        }

        $status = $request->get('status', 'unused');

        $query = UserCoupon::with('coupon')
            ->where('user_id', $userId);

        // 按状态筛选
        switch ($status) {
            case 'unused':
                $query->unused();
                break;
            case 'used':
                $query->used();
                break;
            case 'expired':
                $query->expired();
                break;
        }

        $userCoupons = $query->orderBy('expire_at', 'asc')
            ->orderBy('created_at', 'desc')
            ->paginate(AppConstants::PAGINATION_SHOP_DEFAULT);

        // 获取统计数据
        $stats = $this->couponService->getUserCouponStats($userId);

        return Inertia::render('Shop/Coupons/MyCoupons', [
            'userCoupons' => $userCoupons,
            'status' => $status,
            'stats' => $stats,
        ]);
    }

    /**
     * 领取优惠券
     */
    public function receive(Request $request, $id)
    {
        $userId = auth()->id();
        if (!$userId) {
            return back()->with('error', '请先登录');
        }

        $result = $this->couponService->receive($userId, $id);

        if ($result['success']) {
            return back()->with('success', $result['message']);
        }

        return back()->with('error', $result['message']);
    }

    /**
     * 获取订单可用优惠券
     */
    public function available(Request $request)
    {
        $userId = auth()->id();
        if (!$userId) {
            return response()->json(['coupons' => [], 'message' => '请先登录']);
        }

        $request->validate([
            'order_amount' => 'required|numeric|min:0',
            'items' => 'required|array',
        ]);

        $orderAmount = $request->order_amount;
        $items = $request->items;

        $coupons = $this->couponService->getAvailableCoupons(
            $userId,
            $orderAmount,
            $items
        );

        return response()->json($coupons);
    }
}
